package com.i72.governance.init;



import com.i72.basic.tools.BeanHelper;
import com.i72.basic.context.GlobalContext;
import com.i72.governance.annotation.EnableGovernance;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.Ordered;
import org.springframework.core.type.AnnotationMetadata;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;



//@Import(GovernanceDefaultInit.class)
public class GovernanceInit implements BeanFactoryAware, ImportSelector, Ordered {

    /**
     * 初始化配置全局配置信息。
     * @param factory
     * @throws BeansException
     */
    @Override
    public void setBeanFactory(BeanFactory factory) throws BeansException {

        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory)factory;

        Map m = beanFactory.getBeansWithAnnotation(EnableGovernance.class);

        if(m!=null && m.values().size()>0){
            Collection beanList = (Collection)m.values();

            List beans = new ArrayList(beanList);

            if(beans!=null && beans.size()>0){
                Object bean = beans.get(0);

                Map<String,List<Object>> value = BeanHelper.getAnnotationValue(bean,EnableGovernance.class);

                Boolean register = null;
                if(value.containsKey("register")){
                    register = (Boolean)((List)value.get("register")).get(0);
                }

                Boolean subscribe = null;
                if(value.containsKey("subscribe")){
                    subscribe = (Boolean)((List)value.get("subscribe")).get(0);
                }

                String protocol = null;
                if(value.containsKey("protocol")){
                    protocol = (String)((List)value.get("protocol")).get(0);
                }

                GlobalContext.setRegister(register);
                GlobalContext.setSubscribe(subscribe);
                GlobalContext.setProtocol(protocol);

            }
        }
    }

    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        //这个方法只能导入类，不能导入命名空间
        //被Import注解直接导入的Class，他上面的注解都是无效的
        //本Import注解直接导入的Class，相当于@Bean创建的
        return new String[]{"com.i72.governance.init.GovernanceDefaultInit"};
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE+2;
    }
}
